package com.hadluo.qq.server.mapper;

import com.hadluo.qq.server.entity.Message;
import org.apache.ibatis.annotations.*;
import java.util.List;

/**
 * 消息Mapper接口
 * @author hadluo
 */
@Mapper
public interface MessageMapper {
    /**
     * 根据ID查询消息
     */
    @Select("SELECT * FROM messages WHERE id = #{id}")
    Message selectById(Long id);

    /**
     * 查询用户的未读消息
     */
    @Select("SELECT * FROM messages WHERE receiver_id = #{receiverId} AND status = 0")
    List<Message> selectUnreadMessages(Long receiverId);

    /**
     * 统计未读消息数量
     */
    @Select("SELECT COUNT(*) FROM messages WHERE receiver_id = #{userId} AND status = 0")
    int countUnreadMessages(Long userId);

    /**
     * 查询两个用户之间的最近聊天记录
     */
    @Select("SELECT * FROM messages WHERE (sender_id = #{userId} AND receiver_id = #{friendId}) OR (sender_id = #{friendId} AND receiver_id = #{userId}) ORDER BY create_time DESC LIMIT #{limit}")
    List<Message> selectLatestMessages(@Param("userId") Long userId, @Param("friendId") Long friendId, @Param("limit") int limit);

    /**
     * 查询两个用户之间的聊天记录
     */
    @Select("SELECT * FROM messages WHERE (sender_id = #{userId} AND receiver_id = #{friendId}) OR (sender_id = #{friendId} AND receiver_id = #{userId}) ORDER BY create_time ASC")
    List<Message> selectChatHistory(@Param("userId") Long userId, @Param("friendId") Long friendId);

    /**
     * 插入新消息
     */
    @Insert("INSERT INTO messages (sender_id, receiver_id, type, content, status, create_time, update_time) " +
            "VALUES (#{senderId}, #{receiverId}, #{type}, #{content}, #{status}, #{createTime}, #{updateTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Message message);

    /**
     * 更新消息状态
     */
    @Update("UPDATE messages SET status = #{status} WHERE id = #{id}")
    int updateMessageStatus(@Param("id") Long id, @Param("status") Integer status);

    /**
     * 批量更新消息状态为已读
     */
    @Update("UPDATE messages SET status = 1, update_time = #{updateTime} WHERE receiver_id = #{receiverId} AND sender_id = #{senderId} AND status = 0")
    int batchUpdateStatus(@Param("receiverId") Long receiverId, @Param("senderId") Long senderId, @Param("updateTime") Long updateTime);

    /**
     * 删除消息
     */
    @Delete("DELETE FROM messages WHERE id = #{id}")
    int delete(Long id);

    /**
     * 删除两个用户之间的所有聊天记录
     */
    @Delete("DELETE FROM messages WHERE (sender_id = #{userId} AND receiver_id = #{friendId}) OR (sender_id = #{friendId} AND receiver_id = #{userId})")
    int deleteChatHistory(@Param("userId") Long userId, @Param("friendId") Long friendId);
}